/**
 * 列出搜索出的账号以供选择
 */
import { Radio } from 'antd'
import { OrderedSet } from 'immutable'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import type { BaseAccount } from '@/services/auth'
import type { ChoosingData } from '../hooks'
import './SearchedAccounts.module.less'

export default function SearchedAccounts(
  props: {
    accounts: BaseAccount[]
    multiple: boolean
  } & Pick<ChoosingData, 'locked' | 'choosed' | 'setChoosed'>,
) {
  const { multiple, choosed, locked, accounts, setChoosed } = props

  function handleClick(e: React.MouseEvent<HTMLDivElement>, id: string) {
    e.preventDefault() // 屏蔽 Radio 的奇怪行为：点击白条部分时，会以 input 和 span 为 event.target 触发两次事件，导致无法正确修改状态

    if (choosed.has(id)) setChoosed(choosed.delete(id))
    else if (multiple) setChoosed(choosed.add(id))
    else setChoosed(OrderedSet([id]))
  }

  return <div styleName="searched-accounts">
    {accounts.map(account => {
      const isLocked = locked.has(account.id)
      return <div
        key={account.id}
        styleName="account"
        onClick={isLocked ? undefined : e => handleClick(e, account.id)}
      >
        <Radio disabled={isLocked} checked={choosed.has(account.id)} />
        <img src={account.avatar || defaultAvatar} />
        <span styleName="name">
          {account.name}
          {account.remark ? <span styleName="remark">（{account.remark}）</span> : null}
        </span>
      </div>
    })}
  </div>
}
